<template>
  <div class="register">
    <Header title="注册"/>
    <div class="img">注册</div>
    <van-form @submit="onSubmit">
      <van-cell-group inset>
        <van-field
          v-model="username"
          name="user"
          label="用户名"
          placeholder="用户名"
          :rules="[{ required: true, message: '请填写用户名' }]"
        />
        <van-field
          v-model="password"
          type="password"
          name="pass"
          label="密码"
          placeholder="密码"
          :rules="[{ required: true, message: '请填写密码' }]"
        />
        <van-field
          v-model="password1"
          type="password"
          name="pass1"
          label="确认密码"
          placeholder="确认密码"
          :rules="[{ required: true, message: '请填写密码' }]"
        />
      </van-cell-group>
      <div style="margin: 16px; margin-top: 60px">
        <van-button round block type="primary" native-type="submit">
          注册
        </van-button>
      </div>
      <div style="margin: 16px; margin-top: 60px" @click="loign">
        <van-button round block type="primary" native-type="submit">
          去登录
        </van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import Header from "@/components/Header.vue";
import { reactive, toRefs } from "vue";
import {useRouter} from 'vue-router'
import { showToast } from 'vant';
import 'vant/es/toast/style';
export default {
  components: { Header },
  setup() {
    const router = useRouter()
    const data = reactive({
      username: "",
      password: "",
      password1: "",
    });
    const onSubmit = (values) => {
      console.log("submit", values);
      // 第一:判断本地存储是否已经有用户名
      if(localStorage.userInfo){
        if(localStorage.userInfo['user'] === values['user']){
          showToast('已存在用户，请重新再试！');
          return;
        }
      }else{
        register(values);
      }
    }
    const register = (value)=>{
      // 往本地存储里存储userInfo
      if(value['pass'] === value['pass1']){
        localStorage.setItem('userInfo',JSON.stringify(value))
        showToast('注册成功');
        router.push('/login');
      }else{
        showToast('两次输入密码不一致，请重新再试');
        data.password = ''
        data.password1 = ''
      }
    }
    const loign = ()=>{
        router.push('/login')
    }
    return {
      ...toRefs(data),
      onSubmit,
      loign
    };
  },
};
</script>

<style lang="less" scoped>
.register {
  .img {
    width: 200px;
    height: 200px;
    background-color: #ffc400;
    font-size: 80px;
    line-height: 200px;
    text-align: center;
    border-radius: 40px;
    margin: 20px auto;
  }
  .register {
    margin-top: 20px;
  }
  /deep/ .van-button--primary {
    background-color: #ffc400;
    border: none;
  }
}
</style>